package generator

import (
	"fmt"
	"mall/internal/constant"
	"mall/pkg/util"
	"math/rand"
	"time"
)

// 随机数据源
var (
	RandSource *rand.Rand
)

func init() {
	RandSource = rand.New(rand.NewSource(time.Now().UnixNano()))
}

func formatUniqueKey(uniqueKey string) (res string, err error) {
	keyLen := len(uniqueKey)
	if keyLen > 10 {
		err = constant.ErrInvalidOrderKeyType
	} else if keyLen <= 10 {
		res = fmt.Sprintf("%0*d%s", 10-keyLen, 0, res)
	}
	return
}

// 单号生成器
func GenerateOrderNumber(now time.Time, orderType int, uniqueKey string) (orderNumber string, err error) {
	var orderKey string
	if orderKey, err = formatUniqueKey(uniqueKey); err != nil {
		return
	}
	orderNumber = fmt.Sprintf("%s%02d%s%02d", now.Format(util.NumberLayout),
		orderType, orderKey, RandSource.Intn(100))
	return
}

// 单号批量生成器
func GenerateOrderNumberList(now time.Time, orderType int, uniqueKey string, length int) (result []string, err error) {
	// 后台业务uniqueKey = empID, C端业务uniqueKey = memberID
	if length > 100 {
		err = constant.ErrExceedOrderLimit
		return
	}
	var orderKey string
	if orderKey, err = formatUniqueKey(uniqueKey); err != nil {
		return
	}
	for i := 0; i < length; i++ {
		// 确保连续生成时首单尾号开头随机
		suffix := (now.Nanosecond() + i) % 100
		result = append(result, fmt.Sprintf("%s%02d%s%02d", now.Format(util.NumberLayout),
			orderType, orderKey, suffix))
	}
	return
}
